package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dispatcher.EventDispatcher;
import com.dispatcher.MsgDispatcher;
import com.util.MessageUtil;
import com.util.SHA1;

/**
 * Servlet implementation class WeiXinSerlvet
 */
@WebServlet("/WeiXinSerlvet")
public class WeiXinSerlvet extends HttpServlet {

	private String token = "hello";

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		//接收握手时微信传过来的4个参数
		String signature = request.getParameter("signature");//微信加密签名
		String timestamp = request.getParameter("timestamp");//时间戳
		String nonce = request.getParameter("nonce");//随机数
		String echostr = request.getParameter("echostr");//随机字符串
		//要加密比较的数组
		String[] str = {token,timestamp,nonce};
		// 将token、timestamp、nonce三个参数进行字典序排序：     A:65  a:97
		Arrays.sort(str);
		// 拼接成字符串的时候顺序不能变,因为腾讯服务器传过来就是这样的
		String bigStr=str[0] + str[1] + str[2];
		//进行相同的加密
		String signature2 = new SHA1().getDigestOfString(bigStr.getBytes());
		// 一定要不区分大小写比较.因为微信服务器在传入signature参数时已经转化了小写,但是API并没有提示
		if(signature.equalsIgnoreCase(signature2)){
			// 如果比对成功,则将随机字符串原样返回
			out.write(echostr);
		}else{
			out.write("非法请求");
		}
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Logger logger=Logger.getLogger(WeiXinSerlvet.class);
		// 消息的接收、处理、响应
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
		
		System.out.println("这是 post 方法！");
		try{
			Map<String, String> map=MessageUtil.parseXml(request);//处理用户发送的消息
			String msgtype=map.get("MsgType");//获取消息的类型
			String respXml = "";//接受要返回的xml格式字符串
			//判断是消息还是事件
			if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgtype)){
				// 调用核心业务类接收消息、处理消息
				respXml =  EventDispatcher.processEvent(map); //进入事件处理

			}else{
				// 调用核心业务类接收消息、处理消息
				respXml = MsgDispatcher.processMessage(map);//进入消息处理
			}
			//System.out.println("开发者微信号: "+map.get("ToUserName"));//取出开发者微信号
			// 响应消息(回复消息给客户)
			PrintWriter out = response.getWriter();
			out.print(respXml);
			out.close();
			
		}catch(Exception e){
			logger.error(e,e);
		}
	}

}
